package mod

import (
	"context"
	"github.com/gomodule/redigo/redis"
	"time"
)

func Dial() {
	pool = &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial:        func() (redis.Conn, error) { return redis.Dial("tcp", TCPHost) },
		// 检查空闲连接的连接状态, 若该函数返回错误, 则关闭连接
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			// NOTE: 一分钟一次 ping, 是不是太小了 ?
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
	}
}

func ActiveCount() int {
	return pool.ActiveCount()
}

func Close() error {
	return pool.Close()
}

func Get() redis.Conn {
	return pool.Get()
}

func GetContext(ctx context.Context) (redis.Conn, error) {
	return pool.GetContext(ctx)
}

func IdleCount() int {
	return pool.IdleCount()
}

func Stats() redis.PoolStats {
	return pool.Stats()
}
